import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, Image, Clipboard } from "react-native";
import { Icon } from "@rneui/themed";
import web3Utils from 'web3-utils'
import api from "@/request/api";
import IconNavBar from '@/components/IconNavBar'
import ModalMenu from "@/components/ModalMenu";
import ScanModal from '@/components/ScanModal'
import Loading from "@/components/LoadingModal";
import CommonContext from '@/utils/createContext'
import { sectokenImportProps } from '@/config/navigatorProps'
import { PayWithArray, global } from '@/config/config'

if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer;
const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenImport = (props) => {

    const [menuVisible, setMenuVisible] = useState(false)
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [cameraVisible, setCameraVisible] = useState(false)
    const [address, setSafeAddress] = useState('')
    const [profileImg, setProfileImg] = useState('')
    const [error, setError] = useState(false);

    useEffect(() => {
        let arr = Object.keys(PayWithArray)
        let random = Math.floor(Math.random() * 3)
        let profileImg = arr[random]
        setProfileImg(profileImg)
    }, [])

    useEffect(() => {
        if (address && address.length > 0) {
            checkAddress()
        }
    }, [address])

    const checkAddress = () => {
        //1.检查地址的有效性，调用web3.utils.toChecksumAddress
        let result = web3Utils.checkAddressChecksum(address)
        if (result) {
            setLoadingVisible(true)
            //2.调用接口查询地址的类型，合约地址或普通地址
            api.check_address(address).then(res => {
                if (!(res.result !== '0x')) {
                    setError(true)
                }
                setLoadingVisible(false)
            }).catch(() => {
                setError(true)
                setLoadingVisible(false)
            })
        } else {
            setError(true)
        }
    }

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressOpenMenu = () => {
        setMenuVisible(true)
    }

    const handlePressRightTitle = () => {
        if (!error && address && address.length > 0) {
            props.navigation.navigate({
                name: 'safe-import-name',
                params: {
                    importSafeData: {
                        address,
                        profileImg
                    }
                }
            })
        }
    }

    const handlePressPaste = async () => {
        let content = await Clipboard.getString();
        if (content && content.length > 0) {
            setSafeAddress(content)
        }
        setMenuVisible(false)
    }

    const handlePressScan = () => {
        setMenuVisible(false)
        setCameraVisible(true)
    }

    const handleReadCode = (result) => {
        const { data } = result;
        if (data && data.length > 0) {
            setSafeAddress(data)
        }
        setCameraVisible(false)
    }

    return (
        <View style={{ ...styles.container, backgroundColor: menuVisible ? '#000000' : '#F7F7F7', opacity: menuVisible ? 0.2 : 1 }}>
            <IconNavBar {...props} {...sectokenImportProps} handlePressLeft={handlePressLeft} handlePressRightTitle={handlePressRightTitle} />
            <View style={{ width: width, height: 10 * ratio, backgroundColor: '#FFFFFF' }}></View>
            <View style={{ alignItems: 'center' }}>
                <Text style={{ ...styles.title1, marginTop: 19 * ratio }}>Enter your SE safe address</Text>
                <View style={{ ...styles.addressContent, borderColor: error ? '#FF0000' : '#BDBDBD' }}>
                    {address && address.length > 0 ?
                        <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
                            <Image source={PayWithArray[profileImg]} style={{ ...styles.img, marginLeft: 10 * ratio }} />
                            <Text style={{ ...styles.title2, width: 242 * ratio, marginLeft: 6 * ratio, color: '#2C2C2C' }}>{address}</Text>
                        </View>
                        :
                        <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                            <Text style={{ ...styles.title2, marginLeft: 10 * ratio }}>Enter Safe address</Text>
                            <Icon style={{ marginRight: 15 * ratio }} type='antdesign' name='ellipsis1' color='#979797' size={30} onPress={handlePressOpenMenu} />
                        </View>}
                </View>
                {error && <Text style={{ ...styles.title3, width: 306 * ratio }}>
                    Can not use this address: Safe not found. Please
                    check that the Safe exists on the blockchain
                    (Error 1109)</Text>}
            </View>
            <CommonContext.Provider value={{ modalVisible: menuVisible, setModalVisible: setMenuVisible, handlePressPaste, handlePressScan }}>
                <ModalMenu />
            </CommonContext.Provider>
            <CommonContext.Provider value={{ modalVisible: cameraVisible, setModalVisible: setCameraVisible, handleReadCode }}>
                <ScanModal />
            </CommonContext.Provider>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    title1: {
        fontSize: 16,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 24,
        color: '#2C2C2C'
    },
    title2: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 21,
        color: '#AEAEAE'
    },
    title3: {
        fontSize: 13,
        fontFamily: 'SourceHanSansCN-Regular, SourceHanSansCN',
        fontWeight: '400',
        lineHeight: 18,
        color: '#FF0000'
    },
    addressContent: {
        width: 330 * ratio,
        minHeight: 56 * ratio,
        marginTop: 15 * ratio,
        borderWidth: 1,
        borderRadius: 5
    },
    img: {
        width: 36 * ratio,
        height: 36 * ratio
    }
})
export default SectokenImport